<template>
  <div class="echarts-card-container">
    <h4 :style="{ marginBottom: '0' }" v-if="fullScreenShow">{{ title }}</h4>
    <a-icon type="fullscreen" v-if="option && option.length && fullScreenShow" @click="getFullScreen"></a-icon>
    <div class="echarts-container" v-if="option && option.length">
      <div>
        <div :id="`pie-${index}-${idNum}`" v-for="(item, index) in option" :key="index"></div>
      </div>
    </div>
    <a-empty v-if="!option || !option.length" description="暂无数据" />
  </div>
</template>

<script>
export default{
  name: 'PieEchartsCard',
  props: {
    option: {
      type: Array,
      default: () => []
    },
    title: {
      type: String,
      default: ''
    },
    fullScreenShow: {
      type: Boolean,
      default: true
    },
    idNum: {
      type: String,
      default: ''
    },
    height: {
      type: Number,
      default: 300
    },
    svg: {
      type: Boolean,
      default: true
    }
  },
  data(){
    return{
      myChartList: []
    }
  },
  inject: ["getFullScreenProvide"],
  mounted(){
    //必须使用let
    for(let i=0; i<this.option.length; i++){
      let myChart;
      let dom = document.getElementById(`pie-${i}-${this.idNum}`)
      if(!dom) return;
      let initStyle = () => {
        dom.style.width = (dom.parentNode.clientWidth - 2) / 2 + 'px'
        dom.style.height = `${this.height}px`
      }
      this.$nextTick(() => {
        setTimeout(() => {
          initStyle()
          if(this.svg){
            //将canvas转换成svg, 解决canvas缩放失真
            myChart = this.$echarts.init(dom, null, { renderer : 'svg' })
          }else{
            //dialog中svg格式会出现错乱文字
            myChart = this.$echarts.init(dom)
          }
          myChart.setOption(this.option[i])
          this.myChartList.push(myChart)
        }, 0)
      })
      window.addEventListener('resize', () => {
        if(myChart){
          myChart.dispose()
          myChart = null;
        }
      })
    }
  },
  beforeDestroy(){
    window.removeEventListener('resize', () => {})
    this.myChartList.forEach(item => {
      item.dispose()
      item = null;
    })
  },
  methods: {
    getFullScreen(){
      this.getFullScreenProvide(this.title, this.option)
    }
  }
}
</script>
<style lang="less" scoped>
.echarts-container>div{
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  align-items: center;
}
h4{
  text-align: center;
  font-size: 16px;
  font-weight: 700;
}
.ant-empty{
  height: 300px;
  display: flex;
  flex-direction: column;
  justify-content: center;
}
</style>